<template>
    <div class="container">
      <div class="push-container">
        <div class="header">
          <span class="header-icon"></span>
          <span class="header-title">发布二手商品</span>
        </div>
        
        <!-- 商品图片上传 -->
        <div class="img-list">
          <div class="section-title">商品图片 <span class="required">*</span></div>
          <div class="upload-tip">请上传清晰的商品照片，第一张将作为封面图</div>
          <el-upload
            v-model:file-list="fileList"
            list-type="picture-card"
            :auto-upload="false"
            :on-change="handleFileChange"
            :on-remove="handleRemove"
            :limit="9"
            multiple
            :before-upload="beforeUpload"
            accept="image/*"
            :on-exceed="handleExceed"
            :on-progress="handleProgress"
          >
            <el-icon><Plus /></el-icon>
            <template #tip>
              <div class="upload-progress" v-if="uploading">
                <el-progress
                  :percentage="progressPercent"
                  :stroke-width="16"
                  :format="formatProgress"
                />
              </div>
            </template>
          </el-upload>
        </div>
        
        <el-divider style="margin: 12px 0" />
        
        <!-- 商品信息 -->
        <div class="product-info">
          <div class="form-item">
            <div class="label">商品标题 <span class="required">*</span></div>
            <el-input
              v-model="title"
              maxlength="30"
              show-word-limit
              placeholder="请输入商品标题，30字以内"
            />
          </div>
          
          <div class="form-item">
            <div class="label">商品描述 <span class="required">*</span></div>
            <el-input
              v-model="description"
              type="textarea"
              :rows="5"
              maxlength="500"
              show-word-limit
              placeholder="请详细描述商品的成色、使用感受、入手渠道等信息"
            />
          </div>
          
          <div class="form-item">
            <div class="label">价格 (元) <span class="required">*</span></div>
            <el-input-number
              v-model="price"
              :min="0"
              :precision="2"
              :step="10"
              style="width: 100%"
            />
          </div>
        </div>
        
        <!-- 提交按钮 -->
        <div class="submit">
          <button class="publishBtn" @click="publish">
            <span class="btn-content">发布</span>
          </button>
          <button class="clearBtn" @click="resetForm">
            <span class="btn-content">重置</span>
          </button>
        </div>
      </div>
    </div>
  </template>
  
  <script lang="ts" setup>
  import { ref } from 'vue';
  import { Plus } from '@element-plus/icons-vue';
  import { ElMessage, ElLoading, UploadProps, UploadFile } from 'element-plus';
  import { MarketItemApi } from '@/api/new/MarketItemApi';
  import { TravelNoteApi } from '@/api/new/travelNoteApi';
  import router from '@/router';
  import UserUtil from '@/utils/User/User.js';
  
  // 商品信息
  const title = ref('');
  const description = ref('');
  const price = ref(0);
  
  // 图片上传
  interface UploadFileWithUrl extends UploadFile {
    responseUrl?: string;
  }
  const fileList = ref<UploadFileWithUrl[]>([]);
  const uploadedUrls = ref<string[]>([]);
  const uploading = ref(false);
  const progressPercent = ref(0);
  
  // 处理文件变化
  const handleFileChange: UploadProps["onChange"] = async (uploadFile) => {
    if (!beforeUpload(uploadFile.raw)) {
      return;
    }
    
    uploading.value = true;
    progressPercent.value = 0;
    
    try {
      // 检查是否已存在
      const exists = fileList.value.some(f => f.uid === uploadFile.uid);
      if (exists) return;
      
      // 添加loading状态
      const tempFile = {
        ...uploadFile,
        status: 'uploading',
        percentage: 0
      } as UploadFileWithUrl;
      
      fileList.value = [...fileList.value, tempFile];
      
      // 使用TravelNoteApi.uploadImage上传图片
      const imageUrl = await TravelNoteApi.uploadImage(uploadFile.raw);
      
      // 更新文件状态
      fileList.value = fileList.value.map(f =>
        f.uid === uploadFile.uid
          ? { ...f, status: 'success', responseUrl: imageUrl }
          : f
      );
      
      // 添加到已上传URL列表
      uploadedUrls.value.push(imageUrl);
      
      console.log('上传成功，图片URL:', imageUrl);
      console.log('当前已上传图片列表:', uploadedUrls.value);
      
      uploading.value = false;
      progressPercent.value = 100;
    } catch (error) {
      console.error('上传图片失败:', error);
      
      // 更新文件状态
      fileList.value = fileList.value.map(f =>
        f.uid === uploadFile.uid
          ? { ...f, status: 'fail' }
          : f
      );
      
      ElMessage.error(`上传失败: ${error.message || '未知错误'}`);
      uploading.value = false;
    }
  };
  
  // 进度处理
  const handleProgress: UploadProps['onProgress'] = (event) => {
    progressPercent.value = Math.floor(event.percent);
  };
  
  // 格式化进度显示
  const formatProgress = () => {
    return `${progressPercent.value}%`;
  };
  
  // 文件移除处理
  const handleRemove: UploadProps["onRemove"] = (file) => {
    uploadedUrls.value = uploadedUrls.value.filter(url => url !== (file as UploadFileWithUrl).responseUrl);
    console.log('移除图片后的列表:', uploadedUrls.value);
  };
  
  // 文件类型和大小验证
  const beforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (!rawFile) return false;
    
    if (!['image/jpeg', 'image/png', 'image/webp'].includes(rawFile.type)) {
      ElMessage.error('仅支持 JPG/PNG/WEBP 格式');
      return false;
    }
    if (rawFile.size > 5 * 1024 * 1024) {
      ElMessage.error('图片大小不能超过5MB');
      return false;
    }
    return true;
  };
  
  // 超出限制处理
  const handleExceed: UploadProps['onExceed'] = () => {
    ElMessage.warning('最多可上传9张图片');
  };
  
  // 表单验证
  const validateForm = () => {
    const errors = [];
    if (!title.value.trim()) errors.push('请填写商品标题');
    if (!description.value.trim()) errors.push('请填写商品描述');
    if (price.value <= 0) errors.push('请设置有效的价格');
    if (uploadedUrls.value.length === 0) errors.push('请至少上传一张商品图片');
    
    if (errors.length > 0) {
      ElMessage.warning(errors.join('，'));
      return false;
    }
    return true;
  };
  
  // 发布商品
  const publish = async () => {
    if (!validateForm()) return;
    
    const loading = ElLoading.service({
      lock: true,
      text: '正在发布中...',
      background: 'rgba(0, 0, 0, 0.7)'
    });
    
    try {
      // 获取当前用户ID
      const sellerID = UserUtil.getUserId();
      if (!sellerID) {
        ElMessage.warning('请先登录');
        loading.close();
        return;
      }
      
      // 构建请求参数
      const params = {
        sellerID: sellerID,
        title: title.value,
        description: description.value,
        price: price.value,
        status: 'forSale',
        images: uploadedUrls.value
      };
      
      console.log('发布商品参数:', params);
      
      // 调用MarketItemApi.publishItem发布商品
      const result = await MarketItemApi.publishItem(params);
      
      console.log('发布商品结果:', result);
      
      loading.close();
      ElMessage.success('商品发布成功！');
      
      // 重置表单
      resetForm();
      
      // 发布成功后跳转到二手市场页面
      router.push('/secondhand');
    } catch (error) {
      console.error('发布商品失败:', error);
      loading.close();
      ElMessage.error(`发布失败: ${error.message || '请重试'}`);
    }
  };
  
  // 重置表单
  const resetForm = () => {
    title.value = '';
    description.value = '';
    price.value = 0;
    fileList.value = [];
    uploadedUrls.value = [];
  };
  </script>
  
  <style lang="less" scoped>
  .container {
    flex: 1;
    padding: 0 24px;
    width: 67%;
    max-width: 900px;
    margin: 0 auto;
    
    .push-container {
      background-color: #fff;
      border-radius: 8px;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
      overflow: hidden;
      
      .header {
        padding: 16px 20px;
        border-bottom: 1px solid #f0f0f0;
        display: flex;
        align-items: center;
        
        .header-icon {
          width: 4px;
          height: 16px;
          background-color: #ff2442;
          margin-right: 8px;
          border-radius: 2px;
        }
        
        .header-title {
          font-size: 18px;
          font-weight: 600;
          color: #333;
        }
      }
      
      .img-list {
        padding: 16px 20px;
        
        .section-title {
          font-size: 16px;
          font-weight: 500;
          margin-bottom: 8px;
          
          .required {
            color: #ff2442;
            margin-left: 4px;
          }
        }
        
        .upload-tip {
          font-size: 14px;
          color: #999;
          margin-bottom: 12px;
        }
        
        .upload-progress {
          margin-top: 10px;
          width: 80%;
        }
      }
      
      .product-info {
        padding: 0 20px 20px;
        
        .form-item {
          margin-bottom: 16px;
          
          .label {
            font-size: 14px;
            font-weight: 500;
            margin-bottom: 8px;
            color: #333;
            
            .required {
              color: #ff2442;
              margin-left: 4px;
            }
          }
        }
      }
      
      .submit {
        padding: 0 20px 24px;
        display: flex;
        justify-content: center;
        gap: 16px;
        
        button {
          width: 120px;
          height: 40px;
          font-size: 16px;
          border-radius: 20px;
          border: none;
          cursor: pointer;
          transition: all 0.3s;
        }
        
        .publishBtn {
          background-color: #ff2442;
          color: #fff;
          
          &:hover {
            background-color: #ff3a58;
          }
        }
        
        .clearBtn {
          background-color: #f5f5f5;
          color: #666;
          border: 1px solid #ddd;
          
          &:hover {
            background-color: #eee;
          }
        }
      }
    }
  }
  
  :deep(.el-upload--picture-card) {
    width: 100px;
    height: 100px;
    line-height: 100px;
    border-radius: 8px;
    border: 1px dashed #d9d9d9;
  }
  
  :deep(.el-upload-list--picture-card .el-upload-list__item) {
    width: 100px;
    height: 100px;
    border-radius: 8px;
  }
  
  :deep(.el-upload-list__item-status-label) {
    display: none;
  }
  
  :deep(.el-input-number .el-input__wrapper) {
    padding-left: 12px;
  }
  </style>